const express = require('express')
const mysql = require('mysql2')
const cors = require('cors')

const app = express()
app.use(cors())
app.use(express.json())

// 创建数据库连接
const connection = mysql.createConnection({
  host: 'localhost',
  user: 'your_username',
  password: 'your_password',
  database: 'vue_admin_db'
})

// 文章列表接口
app.get('/vue-element-admin/article/list', (req, res) => {
  const { importance, type, title, page = 1, limit = 20, sort } = req.query
  let query = 'SELECT * FROM articles WHERE 1=1'
  const params = []

  // 构建查询条件
  if (importance) {
    query += ' AND importance = ?'
    params.push(importance)
  }
  if (type) {
    query += ' AND type = ?'
    params.push(type)
  }
  if (title) {
    query += ' AND title LIKE ?'
    params.push(`%${title}%`)
  }

  // 处理排序
  if (sort === '-id') {
    query += ' ORDER BY id DESC'
  }

  // 获取总数
  connection.query('SELECT COUNT(*) as total FROM articles', (err, countResult) => {
    if (err) {
      res.status(500).json({ error: err.message })
      return
    }

    // 分页查询
    const offset = (page - 1) * limit
    query += ' LIMIT ? OFFSET ?'
    params.push(parseInt(limit), parseInt(offset))

    connection.query(query, params, (err, results) => {
      if (err) {
        res.status(500).json({ error: err.message })
        return
      }

      res.json({
        code: 20000,
        data: {
          total: countResult[0].total,
          items: results
        }
      })
    })
  })
})

app.listen(3000, () => {
  console.log('Server running on port 3000')
})